﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;

namespace DTcms.Cache.Redis
{
    public class Cache : ICache
    {
        /// <summary>
        /// 读取缓存
        /// </summary>
        /// <param name="cacheKey">键</param>
        /// <returns></returns>
        public T GetCache<T>(string cacheKey) where T : class
        {
            return RedisCache.Get<T>(cacheKey);
        }

        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <param name="value">对象数据</param>
        /// <param name="cacheKey">键</param>
        public void WriteCache<T>(T value, string cacheKey) where T : class
        {
            //RedisCache.Set(cacheKey, value);
            //配置成与webcache相同时间
            WriteCache(value, cacheKey, DateTime.Now.AddMinutes(10));
        }
        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <param name="value">对象数据</param>
        /// <param name="cacheKey">键</param>
        /// <param name="expires">过期时间(分钟)</param>
        public void WriteCache<T>(T value, string cacheKey, int expires) where T : class
        {
            RedisCache.Set(cacheKey, value, DateTime.Now.AddMinutes(expires));
        }
        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <param name="value">对象数据</param>
        /// <param name="cacheKey">键</param>
        /// <param name="expireTime">到期时间</param>
        public void WriteCache<T>(T value, string cacheKey, DateTime expireTime) where T : class
        {
            RedisCache.Set(cacheKey, value, expireTime);
        }
        /// <summary>
        /// 移除指定数据缓存
        /// </summary>
        /// <param name="cacheKey">键</param>
        public void RemoveCache(string cacheKey)
        {
            RedisCache.Remove(cacheKey);
        }
        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public void RemoveCache()
        {
            RedisCache.RemoveAll();
        }

        /// <summary>
        /// 获取所有缓存名称
        /// </summary>
        /// <param name="prefix">键</param>
        /// <returns></returns>
        public List<string> GetAllCache(List<string> prefix)
        {
            List<string> list = new List<string>();

            var vlist = RedisCache.GetAllKey();
            if (vlist.Count > 0)
            {
                foreach (string t in vlist)
                {
                    if (null != prefix.Find(p => t.StartsWith(p)))
                    {
                        list.Add(t);
                    }
                }
            }
            return list;
        }
    }
}
